package com.qf.web.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.common.base.exception.ServiceException;
import com.qf.common.base.result.ResultCode;
import com.qf.web.common.qo.MsgTemplateParam;
import com.qf.web.config.MsgProperites;
import com.qf.web.dao.BaseRedisDao;
import com.qf.web.service.MsgService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;

/**
 * @author zhangwei
 */
@Service
public class MsgServiceImpl implements MsgService {
    public static final String PREFIX_REDIS_KEY = "msg:phone:";
    private static final String SUCCESS = "OK";
    @Resource
    MsgProperites msgProperites;
    @Resource
    IAcsClient client;
    @Resource
    BaseRedisDao baseRedisDao;
    @Resource
    ObjectMapper objectMapper;

    /**
     * @param phone
     * @return
     */
    @Override
    public void sendMsg(String phone,String key) {
        String number = RandomUtil.randomNumbers(6);
        MsgTemplateParam msgTemplateParam = new MsgTemplateParam();
        msgTemplateParam.setCode(number);
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phone);
        request.setSignName(msgProperites.getSignName());
        request.setTemplateCode(msgProperites.getTemplateCode());
        try {
            request.setTemplateParam(objectMapper.writeValueAsString(msgTemplateParam));
            SendSmsResponse response = client.getAcsResponse(request);
            if (SUCCESS.equals(response.getCode())) {
                //将验证码存储到redis中,并设置有效时间5分钟
                baseRedisDao.setForValue(key + phone, number, Duration.ofMinutes(5));
            }
        } catch (ClientException | JsonProcessingException e) {
            //短信发送异常，抛出异常，让全局处理器处理
            throw new ServiceException(ResultCode.SEND_MSG_ERROR);
        }
    }

}
